"use client"
import React, { createContext, useContext, useReducer } from 'react';

export type TabType = 'car' | 'people' | 'release' | 'my'  | 'startLocation' | 'endLocation' | 'map' //car: 车找人  people： 人找车 release： 发布， my： 我  startLocation: 出发地  endLocation： 目的地 map: 地图信息
type InitialState = {
  tab: TabType
  locationType: 'startLocation' | 'endLocation' | undefined
  local:any
  // local: {
  //   pro: {
  //     code: string
  //     name: string
  //   },
  //   city?: {
  //     code: string
  //     name: string
  //   },
  //   county?: {
  //     code: string
  //     name: string
  //   }
  // }
}
// 初始状态
const initialState : InitialState = {
  tab: 'car',
  locationType: undefined, // 根据 InitialState 定义来设置  
  local: null, // 或者其他合适的初始值  
  // locationType: "startLocation",
  // local: {
  //   pro: {
  //     code: "00",
  //     name:"全国"
  //   }
  // }
};

type StoreContextValue = {  
  state: InitialState;  
  dispatch: React.Dispatch<any>; // Action 是你 dispatch 的动作类型  
};
// 创建一个 Context
const StoreContext = createContext<StoreContextValue | any>(initialState);

type Reducer = (state: InitialState, action: {type: TabType, data?: any}) => InitialState
// 定义 reducer
const reducer: Reducer = (state, action) => {
  switch (action.type) {
    case 'car':
      return { ...state, tab: action.type };
    case 'people':
      return { ...state, tab: action.type };
    case 'release':
      return { ...state, tab: action.type };
    case 'my':
      return { ...state, tab: action.type};
    case 'startLocation':
      return {...state, locationType: 'startLocation'}
    case 'endLocation':
      return {...state, locationType: 'endLocation'}
    case 'map':
      const v = {...state, local: action.data}
      console.log("data", v)
      return {...state, local: action.data}
    default:
      throw new Error('Unhandled action');
  }
}


// 创建 StoreProvider 组件
export function StoreProvider({ children }: {children: React.ReactElement}) {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StoreContext.Provider value={{ state, dispatch }}>
      { children }
    </StoreContext.Provider>
  );
}


// 自定义 hook 用于访问 store
export function useStore() {
  const context = useContext(StoreContext);
  if (!context) {
    throw new Error('useStore must be used within a StoreProvider');
  }
  return context;
}